import { Body, Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { Context } from '@midwayjs/koa';
import { DoupiaopiaoCommissionEntity } from '../entity/commission';
import { DoupiaopiaoInvitationEntity } from '../entity/invitation';
import { DoupiaopiaoUserEntity } from '../entity/user';
import { DoupiaopiaoOrderEntity } from '../entity/order';
import { DoupiaopiaoWithdrawEntity } from '../entity/withdraw';
import { Any, Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { In } from 'typeorm';

/**
 * 分佣相关
 */
@Provide()
export class DoupiaopiaoCommissionService extends BaseService {
  @Inject()
  doupiaopiaoCommissionService: DoupiaopiaoCommissionService;
  @InjectEntityModel(DoupiaopiaoCommissionEntity)
  doupiaopiaoCommissionEntity: Repository<DoupiaopiaoCommissionEntity>;
  @InjectEntityModel(DoupiaopiaoInvitationEntity)
  doupiaopiaoInvitationEntity: Repository<DoupiaopiaoInvitationEntity>;
  @InjectEntityModel(DoupiaopiaoUserEntity)
  doupiaopiaoUserEntity: Repository<DoupiaopiaoUserEntity>;
  @InjectEntityModel(DoupiaopiaoWithdrawEntity)
  doupiaopiaoWithdrawEntity: Repository<DoupiaopiaoWithdrawEntity>;
  @InjectEntityModel(DoupiaopiaoOrderEntity)
  doupiaopiaoOrderEntity: Repository<DoupiaopiaoOrderEntity>;

  @Inject()
  ctx: Context;
  // 获取粉丝列表
  async getList(query) {
    const { userId } = this.ctx.app_userinfo;

    const [res, total] = await this.doupiaopiaoInvitationEntity.findAndCount({
      where: { shareUserId: userId },
      skip: (query.page - 1) * query.size,
      take: query.size,
      order: { createTime: 'DESC' },
    });
    const list = await Promise.all(
      res.map(async item => {
        const user = await this.doupiaopiaoUserEntity.findOneBy({
          id: parseInt(item.userId),
        });

        if (parseInt(item.userId) == user.id) {
          item['dyName'] = user.nickName;
          item['dyImage'] = user.headImg;
        }

        return item;
      })
    );
    const totalPages = Math.ceil(total / query.size);
    return {
      list,
      page: parseInt(query.page),
      size: parseInt(query.size),
      total,
      totalPages,
    };
  }
  //获取当前的粉丝(今日新增 本月新增)
  async getFansNum(query) {
    const { userId } = this.ctx.app_userinfo;
    const res = await this.doupiaopiaoInvitationEntity.find({
      where: { shareUserId: userId },
    });
  }

  //获取当前所有粉丝的订单列表
  async getOrderList(query) {
    // const { userId } = this.ctx.app_userinfo;
    // const result = await this.doupiaopiaoCommissionEntity.find({
    //   where: { payState: 1, userId },
    // });
    // let list = [];
    // for (const item of result) {
    //   const order = await this.doupiaopiaoOrderEntity.findOneBy({
    //     orderNo: item.orderId,
    //   });
    //   if (order) {
    //     const user = await this.doupiaopiaoUserEntity.findOneBy({
    //       id: parseInt(order.userId),
    //     });
    //     item['movieName'] = order.movieName;
    //     item['ticketNum'] = order.ticketNum;
    //     item['dyName'] = user.nickName;
    //     item['dyImage'] = user.headImg;
    //   }
    //   list.push(item);
    // }
    // return list;
    const { userId } = this.ctx.app_userinfo;
    const skip = (query.page - 1) * query.size;

    const [result, totalCount] = await Promise.all([
      this.doupiaopiaoCommissionEntity.find({
        where: { payState: 1, userId },
        skip,
        take: query.size,
        order: { createTime: 'DESC' },
      }),
      this.doupiaopiaoCommissionEntity.count({
        where: { payState: 1, userId },
      }),
    ]);

    const list = [];
    for (const item of result) {
      const order = await this.doupiaopiaoOrderEntity.findOneBy({
        orderNo: item.orderId,
      });
      if (order) {
        const user = await this.doupiaopiaoUserEntity.findOneBy({
          id: parseInt(order.userId),
        });
        item['movieName'] = order.movieName;
        item['ticketNum'] = order.ticketNum;
        item['dyName'] = user.nickName;
        item['dyImage'] = user.headImg;
      }
      list.push(item);
    }

    const totalPages = Math.ceil(totalCount / query.size);

    return {
      list,
      page: parseInt(query.page),
      size: parseInt(query.size),
      totalCount,
      totalPages,
    };
  }
  //用户进行提现
  async withDraw(query) {
    const { userId } = this.ctx.app_userinfo;
    const user = await this.doupiaopiaoUserEntity.findOneBy({
      id: userId,
    });
    if (user) {
      user.balance = user.balance - query.withDrawMoney * 100;
      await this.doupiaopiaoUserEntity.save(user);

      await this.doupiaopiaoWithdrawEntity.save({
        userId: user.id.toString(),
        zfbCount: query.zfbCount,
        amount: query.withDrawMoney * 100,
        totalMoney: query.totalMoney * 100,
        serviceCharge: 0,
        type: query.type,
        state: 1,
        withdrawType: 2,
      });
      return { data: '提现成功', code: 200 };
    }
  }
  //获取提现的列表
  async getWithHistory(query) {
    // const { userId } = this.ctx.app_userinfo;
    // const result = await this.doupiaopiaoWithdrawEntity.find({
    //   where: { state: query.state, userId },
    // });
    // console.log(result);
    // return result;
    const { userId } = this.ctx.app_userinfo;
    const { page, size, state } = query;
    const offset = (page - 1) * size;

    const [rows, count] = await this.doupiaopiaoWithdrawEntity.findAndCount({
      where: { state, userId },
      skip: offset,
      take: size,
      order: { createTime: 'DESC' },
    });
    // const reversedRows = rows.reverse(); // 反转 rows 数组，将最新的数据放在前面
    const totalPages = Math.ceil(count / size);

    console.log(rows);
    return {
      data: rows,
      pagination: {
        page,
        size,
        totalPages,
        totalItems: count,
      },
    };
  }
  //获取一下关于佣金的数据
  async getCommissionData(query) {
    const { userId } = this.ctx.app_userinfo;
    const res = await this.doupiaopiaoWithdrawEntity.find({
      where: { userId, state: 2 },
    });
    const waitRes = await this.doupiaopiaoWithdrawEntity.find({
      where: { userId, state: 1 },
    });
    const inivate = await this.doupiaopiaoInvitationEntity.find({
      where: { shareUserId: userId },
    });

    const commissionRes = await this.doupiaopiaoCommissionEntity.find({
      where: { userId: userId },
    });
    const accumulatedCommission = commissionRes.reduce(
      (total, order) => (total * 100 + order.endPrice * 100) / 100,
      0
    );

    // // -------------

    // // 查询邀请关系表中的邀请人为指定用户的记录，并获取被邀请人的 userId
    // const invitedUsers = await this.doupiaopiaoInvitationEntity.find({
    //   where: { shareUserId: userId },
    //   select: ['userId'],
    // });

    // // 构造被邀请人的 userId 数组，用于查询分佣订单表
    // const invitedUserIds = invitedUsers.map(invitedUser => invitedUser.userId);

    // // 查询分佣订单表中符合被邀请人 userId 数组的记录，并获取佣金金额
    // const commissionOrders = await this.doupiaopiaoCommissionEntity.find({
    //   where: { userId: In(invitedUserIds) },
    //   select: ['endPrice'],
    // });

    // // 计算累计佣金
    // const accumulatedCommission = commissionOrders.reduce(
    //   (total, order) => (total * 100 + order.endPrice * 100) / 100,
    //   0
    // );
    const inivateNum = inivate.length;
    const totalWithdrawAmount = res.reduce(
      (total, obj) => total + obj.amount,
      0
    ); //已经提现的金额
    const waitAmount = waitRes.reduce((total, obj) => total + obj.amount, 0); //提现中

    return {
      accumulatedCommission,
      inivateNum,
      totalWithdrawAmount,
      waitAmount,
    };
  }
}
